package com.drama.outtake.comopnen;

import com.drama.outtake.domain.CartItem;
import com.drama.outtake.domain.Product;
import com.drama.outtake.domain.ShopOfCart;
import com.drama.outtake.dto.ShopDto;
import com.drama.outtake.service.IProductService;
import com.drama.outtake.service.IShopService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : 李先均
 * @Date 2023/3/29 10:06
 */
@Component
@RequiredArgsConstructor
public class ShopOfCartComponent {
    private final IProductService productService;
    private final IShopService shopService;

    public void syncData(ShopOfCart shop) {
        shop.getCartItems().forEach(cartItem -> {
            Product product = productService.getProductById(cartItem.getProductId());
            cartItem.setPackagePrice(product.getPackagePrice());
            cartItem.setPrice(cartItem.getPrice());
            cartItem.setPicture(product.getPicture());
        });
        double amountPrice = shop.getCartItems().stream()
                .mapToDouble(cartItem -> cartItem.getNumber() * cartItem.getPrice())
                .sum();
        double amountPackagePrice = shop.getCartItems().stream()
                .mapToDouble(cartItem -> cartItem.getNumber() * cartItem.getPackagePrice())
                .sum();
        int amountNumber = shop.getCartItems().stream()
                .mapToInt(CartItem::getNumber)
                .sum();
        ShopDto shopDto = shopService.getShopDetailById(shop.getShopId()).getShop();
        List<CartItem> cartItems = shop.getCartItems().stream().filter(cartItem -> cartItem.getNumber() > 0).collect(Collectors.toList());
        shop.setAmountPrice(amountPrice);
        shop.setAmountPackagePrice(amountPackagePrice);
        shop.setAmountNumber(amountNumber);
        shop.setMoa(shopDto.getMoa());
        shop.setShopName(shopDto.getName());
        shop.setCartItems(cartItems);
    }
}
